package com.taiyi.renaissancemall.ui.mine.order.detail

import android.app.Dialog
import android.content.Intent
import android.os.Bundle
import android.os.Handler
import android.os.Message
import android.view.LayoutInflater
import android.view.View
import android.view.View.GONE
import android.view.View.VISIBLE
import com.alipay.sdk.app.PayTask
import com.taiyi.renaissancemall.R
import com.taiyi.renaissancemall.Utils.PayResult
import com.taiyi.renaissancemall.Utils.ToastUtils
import com.taiyi.renaissancemall.Utils.load
import com.taiyi.renaissancemall.base.BaseActivity
import com.taiyi.renaissancemall.base.MyApp
import com.taiyi.renaissancemall.bean.*
import com.taiyi.renaissancemall.ui.main.paysuccess.PaySuccessActivity
import com.taiyi.renaissancemall.ui.mine.address.ShippingAddressActivity
import com.taiyi.renaissancemall.ui.mine.order.MyOrderActivity
import com.taiyi.renaissancemall.ui.mine.order.evaluation.EvaluationActivity
import com.taiyi.renaissancemall.ui.mine.order.orderExpress.OrderExpressActivity
import com.taiyi.renaissancemall.ui.mine.order.sale.ApplySaleActivity
import com.tencent.mm.opensdk.modelpay.PayReq
import kotlinx.android.synthetic.main.activity_order_detail.*
import kotlinx.android.synthetic.main.base_top_white_background_layout.*
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe

class OrderDetailActivity : BaseActivity<OrderDetailView, OrderDetailPresent>(), OrderDetailView {

    override fun getLayoutId(): Int = R.layout.activity_order_detail

    lateinit var orderType: String
    lateinit var myOrdercommodityid: String
    lateinit var mDialog: Dialog
    lateinit var myOrderId: String

    var payMethod = "2"

    override fun initPresenter(): OrderDetailPresent = OrderDetailPresent()

    override fun initViews(savedInstanceState: Bundle?) {
        titleTv.text = getString(R.string.orderDetail)
        EventBus.getDefault().register(this)
        orderType = intent.extras?.getString("orderType")!!
        myOrderId = intent.extras?.getString("orderId")!!
        myOrdercommodityid = intent.extras?.getString("ordercommodityid")!!
        aliPayTv.isSelected = true

        mDialog = Dialog(this, R.style.MyDialog)
        val view = LayoutInflater.from(this)
            .inflate(R.layout.cancel_order_dialog_layout, null)
        mDialog.setContentView(view)
        view.findViewById<View>(R.id.thinkAgainTv)
            .setOnClickListener { mDialog.dismiss() }

        view.findViewById<View>(R.id.confirmTv)
            .setOnClickListener {
                mDialog.dismiss()
                showProgress()
                presenter.cancelOrder()
            }
    }

    @Subscribe
    fun updateAddress(address: AddressListBean.AddresslistBean) {

    }

    override fun initData() {
        showProgress()
        presenter.getOrderDetail()
    }

    override fun initImmersionBar() {
        super.initImmersionBar()
        mImmersionBar.titleBar(top).init()
    }

    override fun initEvent() {
        backIv.setOnClickListener { finish() }
        aliPayTv.setOnClickListener {
            //支付宝支付
            payMethod = "2"
            aliPayTv.isSelected = true
            weChatTv.isSelected = false
            balancePaymentTv.isSelected = false
        }
        weChatTv.setOnClickListener {
            //微信支付
            payMethod = "1"
            aliPayTv.isSelected = false
            weChatTv.isSelected = true
            balancePaymentTv.isSelected = false
        }
        balancePaymentTv.setOnClickListener {
            //余额支付
            payMethod = "3"
            aliPayTv.isSelected = false
            weChatTv.isSelected = false
            balancePaymentTv.isSelected = true
        }
        paymentTv.setOnClickListener {
            //待付款
            //付款
            showProgress()
            presenter.commitOrder()
        }
        cancelOrderTv.setOnClickListener {
            //待付款
            //取消订单
            mDialog.show()
        }
        updateAddressTv.setOnClickListener {
            //待付款
            //修改地址
            var intent = Intent(this, ShippingAddressActivity::class.java)
            intent.putExtra("ordercommodityid", myOrdercommodityid)
            startActivity(intent)
        }
        remindTv.setOnClickListener {
            //待发货
            //提现发货
            showProgress()
            presenter.remind()
        }
        applySaleTv.setOnClickListener {
            var orderListBean = OrderListBean.OrderlistBean()
            orderListBean.smallimgurl =
                myDetailBean.order.smallimgurl
            orderListBean.name = myDetailBean.order.name
            orderListBean.typename = myDetailBean.order.typename
            orderListBean.number = myDetailBean.order.number
            orderListBean.hyprice = myDetailBean.order.hyprice
            orderListBean.price = myDetailBean.order.price
            orderListBean.ordercommodityid = myDetailBean.order.ordercommodityid

            //待发货
            //申请售后
            val intent = Intent(
                this,
                ApplySaleActivity::class.java
            )

            intent.putExtra("product", orderListBean)
            intent.putExtra("ifHui", myDetailBean.ifhui)
            startActivity(intent)
        }
        confirmReceiptTv.setOnClickListener {
            //待收货
            //确认收货
            showProgress()
            presenter.confirmReceived()
        }
        viewLogisticsTv.setOnClickListener {
            //待收货
            //查看物流
            val intent = Intent(
                this,
                OrderExpressActivity::class.java
            )
            intent.putExtra("ocId", myOrdercommodityid)
            startActivity(intent)
        }
        receiptApplySaleTv.setOnClickListener {
            //待收货
            //申请售后
            var orderListBean = OrderListBean.OrderlistBean()
            orderListBean.smallimgurl =
                myDetailBean.order.smallimgurl
            orderListBean.name = myDetailBean.order.name
            orderListBean.typename = myDetailBean.order.typename
            orderListBean.number = myDetailBean.order.number
            orderListBean.hyprice = myDetailBean.order.hyprice
            orderListBean.price = myDetailBean.order.price
            orderListBean.ordercommodityid = myDetailBean.order.ordercommodityid
            val intent = Intent(
                this,
                ApplySaleActivity::class.java
            )

            intent.putExtra("product", orderListBean)
            intent.putExtra("ifHui", myDetailBean.ifhui)
            startActivity(intent)
        }
        evaluationTv.setOnClickListener {
            //待评价
            //评价
            val intent = Intent(
                this,
                EvaluationActivity::class.java
            )
            intent.putExtra("oId", myOrdercommodityid)
            startActivity(intent)
        }

        evaluationApplySaleTv.setOnClickListener {
            //待评价
            //申请售后
            var orderListBean = OrderListBean.OrderlistBean()
            orderListBean.smallimgurl =
                myDetailBean.order.smallimgurl
            orderListBean.name = myDetailBean.order.name
            orderListBean.typename = myDetailBean.order.typename
            orderListBean.number = myDetailBean.order.number
            orderListBean.hyprice = myDetailBean.order.hyprice
            orderListBean.price = myDetailBean.order.price
            orderListBean.ordercommodityid = myDetailBean.order.ordercommodityid
            val intent = Intent(
                this,
                ApplySaleActivity::class.java
            )
            intent.putExtra("product", orderListBean)
            startActivity(intent)
        }


    }

    val SDK_PAY_FLAG = 1001
    var aliPayOrderId = ""
    private val mHandler: Handler = object : Handler() {

        override fun handleMessage(msg: Message) {
            when (msg.what) {
                SDK_PAY_FLAG -> {
                    var payResult = PayResult(msg.obj as MutableMap<String, String>?)
                    var resultInfo = payResult.result
                    if (payResult?.resultStatus == "9000") {
                        showProgress()
                        presenter.findOrderState()
                    }

                }
                else ->
                    ToastUtils.showLongToast("支付异常")
            }

        }
    }

    override fun getOrderId(): String = intent.extras?.getString("ordercommodityid")!!
    override fun commitOrderSuccess(commitOrderBean: CommitOrderBean?) {

        hideProgress()
        aliPayOrderId = commitOrderBean?.orderid!!
        if ("2" == payMethod) {//支付宝支付
            val stInfo = commitOrderBean?.aliparam
            var payRunnable = Runnable {
                var alipay = PayTask(this)
                var result = alipay.payV2(stInfo, true)
                var msg = Message()
                msg.what = SDK_PAY_FLAG
                msg.obj = result
                mHandler.sendMessage(msg)
            }
            var payThread = Thread(payRunnable)
            payThread.start()

        } else if ("3" == payMethod) {//余额支付
            showProgress()
            presenter.findOrderState()
        } else if ("1" == payMethod) {//微信支付
            //这里的appid，替换成自己的即可
            var api = MyApp.getWxApi()
            api.registerApp(MyApp.getAppId())
            //这里的bean，是服务器返回的json生成的bean
            var payRequest = PayReq();
            payRequest.appId = commitOrderBean.appid
            payRequest.partnerId = commitOrderBean.partnerid
            payRequest.prepayId = commitOrderBean.prepayid
            payRequest.packageValue = "Sign=WXPay";//固定值
            payRequest.nonceStr = commitOrderBean.noncestr
            payRequest.timeStamp = commitOrderBean.timestamp
            payRequest.sign = commitOrderBean.sign

            //发起请求，调起微信前去支付
            api.sendReq(payRequest);
        }


    }

    lateinit var myDetailBean: OrderDetailBean

    override fun getOrderStateSuccess() {
        hideProgress()
        var intent = Intent(this, PaySuccessActivity::class.java)
        intent.putExtra("payWay", payMethod)
        intent.putExtra(
            "payAmount",
            (myDetailBean?.order?.yunfei?.toDouble()?.plus(myDetailBean?.order?.sumprice?.toDouble()!!)).toString()
        )
        intent.putExtra("orderId", aliPayOrderId);
        startActivity(intent)
        finish()
    }

    override fun getOrderStateFailure(msg: String?) {

    }

    override fun getSelPayMethod(): String = payMethod
    override fun confirmFailure(msg: String?) {
        hideProgress()
        toast(msg)
    }

    override fun confirmSuccess() {//
        hideProgress()
        val intent = Intent(
            this,
            MyOrderActivity::class.java
        )
        intent.putExtra("type", 3)
        startActivity(intent)
        finish()
    }

    override fun cancelOrderFailure(msg: String?) {
        hideProgress()
        toast(msg)
    }

    override fun cancelOrderSuccess() {
        hideProgress()
        finish()
    }

    override fun commitOrderFailure(msg: String?) {
        hideProgress()
        toast(msg)
    }

    override fun getOrderInfoSuccess(detailBean: OrderDetailBean?) {
        hideProgress()
        myDetailBean = detailBean!!
        when (orderType) {
            "0" -> {//待付款
                orderStateTv.text = getString(R.string.unPaid)
                dfkGroup.visibility = VISIBLE
                paymentMethodGroup.visibility = VISIBLE
            }
            "1" -> {//待发货
//                var xcday = detailBean?.order?.xcday
                orderStateTv.text = "待发货"
                dfhGroup.visibility = VISIBLE
                payTime.visibility = VISIBLE
                payTimeTv.visibility = VISIBLE
            }
            "2" -> {//待收货
                presenter.getLogisticsInfo()
                var xcday = detailBean?.order?.xcday
                orderStateTv.text = "已发货，还剩$xcday" + "天自动确认"
                logisticsGroup.visibility = VISIBLE
                dshGroup.visibility = VISIBLE
                payTime.visibility = VISIBLE
                payTimeTv.visibility = VISIBLE
                shipTime.visibility = VISIBLE
                shipTimeTv.visibility = VISIBLE
            }
            "3" -> {//待评价
                orderStateTv.text = "交易完成"
                if (detailBean?.order?.shou_type == "1") {
                    evaluationApplySaleTv.visibility = VISIBLE
                } else {
                    evaluationApplySaleTv.visibility = GONE
                }
                evaluationTv.visibility = VISIBLE
                payTime.visibility = VISIBLE
                payTimeTv.visibility = VISIBLE
                shipTime.visibility = VISIBLE
                shipTimeTv.visibility = VISIBLE
            }
            "4" -> {//已完成
                orderStateTv.text = "已完成"
                payTime.visibility = VISIBLE
                payTimeTv.visibility = VISIBLE
                shipTime.visibility = VISIBLE
                shipTimeTv.visibility = VISIBLE
            }
            "5" -> {//售后
                var returnType = intent.getStringExtra("returnType")
                when (returnType) {
                    "0" -> orderStateTv.text = "无申请"
                    "1" -> orderStateTv.text = "申请退货中"
                    "2" -> orderStateTv.text = "同意退货"
                    "3" -> orderStateTv.text = "拒绝退货"
                    "4" -> orderStateTv.text = "退货成功"
                    "5" -> orderStateTv.text = "退货失败"
                    "6" -> orderStateTv.text = "申请退款中"
                    "7" -> orderStateTv.text = "退款成功"
                    "8" -> orderStateTv.text = "退款失败"
                    "9" -> orderStateTv.text = "拒绝退款"
                    "10" -> orderStateTv.text = "同意退款"
                    "11" -> orderStateTv.text = "申请换货中"
                    "12" -> orderStateTv.text = "同意换货"
                    "13" -> orderStateTv.text = "换货已发货"
                    "14" -> orderStateTv.text = "换货成功"
                    "15" -> orderStateTv.text = "换货失败"
                    "16" -> orderStateTv.text = "拒绝换货"
                }
            }
        }
        receiverNameTv.text = detailBean?.order?.addname
        shippingAddressTv.text =
            detailBean?.order?.provincename + detailBean?.order?.cityName + detailBean?.order?.areaName + detailBean?.order?.address
        phoneNumberTv.text = getString(R.string.contactNumber) + "  " + detailBean?.order?.tel
        productIv.load(detailBean?.order?.smallimgurl!!)
        productNameTv.text = detailBean?.order?.name
        quantityTv.text = "x" + detailBean?.order?.number
        specTv.text = detailBean?.order?.typename
        priceTv.text = "￥" + detailBean?.order?.price
        totalPriceTv.text = "￥" + detailBean?.order?.sumprice
        freightTv.text = "￥" + detailBean?.order?.yunfei
        totalTv.text =
            "￥" + (detailBean?.order?.yunfei?.toDouble()?.plus(detailBean?.order?.sumprice?.toDouble()!!))
        orderNumberTv.text = detailBean?.order?.ordercommodityid.toString()
        createTimeTv.text = detailBean?.order?.createtime
        shipTimeTv.text = detailBean?.order?.rent_time
        payTimeTv.text = detailBean?.order?.paycreatetime
        getBvTv.text = detailBean?.order?.bvsumprice + "BV"
        remarksTv.text = when (detailBean?.order?.remark) {
            "" -> "无"
            null -> "无"
            else -> detailBean?.order?.remark
        }
        when (detailBean?.order?.payment_type) {
            "1" ->
                payWayTv.text = getString(R.string.weChat)
            "2" ->
                payWayTv.text = getString(R.string.aliPay)
            "3" ->
                payWayTv.text = getString(R.string.balance)
        }
        availableBalanceTv.text = "(可用余额${detailBean.user.liquannumti}元)"

    }

    override fun getOrderExpressSuccess(orderExpressListBean: OrderExpressListBean?) {
        hideProgress()
        var data = orderExpressListBean?.orderExpress?.express?.data
        if (data != null && data.size > 0)
            logisticsInfoTv.text = data!![0].context
        else
            logisticsInfoTv.text = "暂无物流信息"
    }

    override fun getParentOrderId(): String = myOrderId

    override fun remindFailure(msg: String?) {
        hideProgress()
        toast(msg)
    }

    override fun getOrderInfoFailure(msg: String?) {
        hideProgress()
        toast(msg)
    }

    override fun getOrderExpressFailure(msg: String?) {
        hideProgress()
        toast(msg)
    }

    override fun remindSuccess() {
        hideProgress()
    }
}
